package com.dlc.yunguang.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.dlc.commonlibrary.dialog.WaitingDialog;
import com.dlc.commonlibrary.utils.LogPlus;
import com.dlc.commonlibrary.widget.CommonItemView;
import com.dlc.commonlibrary.widget.popup.CommonPopupList;
import com.dlc.yunguang.adapter.OrderAdapter;
import com.dlc.yunguang.net.bean.HotelBean;
import com.dlc.yunguang.net.bean.OrderBean;
import com.dlc.yunguang.net.bean.OrderDetailBean;
import com.dlc.yunguang.net.exception.ErrorMsgException;
import com.dlc.yunguang.net.protocol.OrderProto;
import com.dlc.yunguang.net.protocol.StockProto;
import com.dlc.yunguang.net.protocol.base.HttpProtocol;
import com.dlc.yunguang.R;
import com.dlc.yunguang.activity.OrderDetailActivity1;
import com.holenzhou.pullrecyclerview.PullRecyclerView;
import com.holenzhou.pullrecyclerview.layoutmanager.XLinearLayoutManager;
import java.util.ArrayList;
import java.util.List;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/7/19 0019.
 */

public class SendGoodsOddFragment extends Fragment {
    @BindView(R.id.order_rv)
    PullRecyclerView order_rv;
    @BindView(R.id.tv_hotel)
    TextView mTvHotel;
    @BindView(R.id.drop_hotel)
    FrameLayout mDropHotel;
    @BindView(R.id.item_hotel)
    CommonItemView mItemHotel;
    private OrderAdapter orderAdapter;
    private List<OrderBean.DataBean.ListBean> orderBeanList = new ArrayList<>();
    private int presentPage = 1;
    private boolean isRefresh = true;
    private int pageSize = 20;
    private WaitingDialog mDialog;
    private CommonPopupList mHotelPopup;//酒店
    List<HotelBean.DataBean> HotelList = new ArrayList<>();
    private String HotelId = null;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
        Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_send_goods_odd, container, false);
        ButterKnife.bind(this, view);
        initData();
        return view;
    }
    @OnClick({ R.id.drop_hotel })
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.drop_hotel:
                mHotelPopup.showAsDropDown(view);
                break;

        }
    }


    private void initData() {
        orderAdapter =
            new OrderAdapter(getActivity(), R.layout.item_order_manage, orderBeanList, 1);
        order_rv.setAdapter(orderAdapter);
        order_rv.setLayoutManager(new XLinearLayoutManager(getActivity()));
        order_rv.setColorSchemeResources(android.R.color.holo_blue_light,
            android.R.color.holo_red_light, android.R.color.holo_orange_light,
            android.R.color.holo_green_light); // 设置下拉刷新的旋转圆圈的颜色
        order_rv.enablePullRefresh(true); // 开启下拉刷新，默认即为true，可不用设置
        order_rv.enableLoadDoneTip(true, R.string.load_done_tip); // 开启数据全部加载完成时的底部提示，默认为false
        order_rv.setOnRecyclerRefreshListener(new PullRecyclerView.OnRecyclerRefreshListener() {

            @Override
            public void onPullRefresh() {
                order_rv.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        isRefresh = true;
                        orderBeanList.clear();
                        presentPage = 1;
                        loadListData();
                    }
                }, 1500);
            }

            @Override
            public void onLoadMore() {
                order_rv.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        isRefresh = false;
                        presentPage++;
                        loadListData();
                    }
                }, 1500);
            }
        });
        order_rv.postRefreshing();
        mHotelPopup = CommonPopupList.newBuilder(getActivity())
            .setWidthEquals(mDropHotel)
            .setOnSelectItemListener(new CommonPopupList.OnSelectItemListener() {
                @Override
                public void onSelectItem(CommonPopupList popup, String item, int position) {
                    popup.dismiss();
                    // TODO: 2017/7/20
                    mTvHotel.setText(item);
                    if (HotelList != null) {
                        HotelId = HotelList.get(position).getId();
                        presentPage = 1;
                        loadListData();
                    }
                }
            })
            .build();

        getPopupListData();
    }

    private void getPopupListData() {
        OrderProto.get().getHotel().
            subscribeOn(Schedulers.io()).
            observeOn(AndroidSchedulers.mainThread()).
            subscribe(new Observer<HotelBean>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {
                    LogPlus.e(e.getMessage());
                }

                @Override
                public void onNext(HotelBean hotelBean) {
                    if (hotelBean != null && hotelBean.getData() != null) {
                        List<String> datas = new ArrayList<>();

                        HotelBean.DataBean bean1 = new HotelBean.DataBean();
                        bean1.setTitle(getString(R.string.choose_all));
                        HotelList.add(bean1);
                        for (int i = 0; i < hotelBean.getData().size(); i++) {
                            HotelList.add(hotelBean.getData().get(i));
                        }
                        datas.add(getString(R.string.choose_all));
                        for (HotelBean.DataBean bean : hotelBean.getData()) {
                            datas.add(bean.getTitle());
                        }
                        mHotelPopup.setData(datas);
                    }
                }
            });
    }

    private void loadListData() {
        StockProto.get()
            .getOrder("order_deliver", String.valueOf(presentPage), String.valueOf(pageSize),HotelId,
                new HttpProtocol.Callback<OrderBean>() {
                    @Override
                    public void onSuccess(OrderBean msgBean) {
                        onGetSuccess(msgBean);
                    }

                    @Override
                    public void onFailed(int code, ErrorMsgException e) {
                        Log.d("送货列表获取失败的数据---->", e.getMessage());
                    }
                });
    }

    public void onGetSuccess(OrderBean msgBean) {
        int pageSize;
        if (presentPage == 1) {
            orderBeanList.clear();
        }
        pageSize = msgBean.data.totalpage;
        for (int i = 0; i < msgBean.data.list.size(); i++) {
            OrderBean.DataBean.ListBean dataBean = msgBean.data.list.get(i);
            orderBeanList.add(dataBean);
        }
        orderAdapter.notifyDataSetChanged();
        orderAdapter.setOnItemClickListener(new OrderAdapter.OnItemClickListener() {
            @Override
            public void onClick(int position, String id) {
                showLoadingDialog();
                getDetailData(id);
            }
        });
        if (isRefresh) {
            if (order_rv != null) {
                order_rv.stopRefresh();
                order_rv.enableLoadMore(pageSize > 1); // 当剩余还有大于0页的数据时，开启上拉加载更多
                if (orderBeanList.size() == 0) {
                    Toast.makeText(getActivity(), "数据为空", Toast.LENGTH_SHORT).show();
                    return;
                }
            }
        } else {
            if (order_rv != null) {
                order_rv.stopLoadMore();
                order_rv.enableLoadMore(pageSize > presentPage);
            }
        }
    }

    private void getDetailData(String id) {
        StockProto.get()
            .getOrderDetail("order_deliver_detail", id,
                new HttpProtocol.Callback<OrderDetailBean>() {
                    @Override
                    public void onSuccess(OrderDetailBean orderDetailBean) {
                        dismissLoadingDialog();
                        Toast.makeText(getActivity(), orderDetailBean.msg, Toast.LENGTH_SHORT)
                            .show();
                        Intent intent = new Intent(getActivity(), OrderDetailActivity1.class);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("detailData", orderDetailBean);
                        intent.putExtras(bundle);
                        intent.putExtra("type", 1);
                        startActivity(intent);
                    }

                    @Override
                    public void onFailed(int code, ErrorMsgException e) {
                        Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
                        dismissLoadingDialog();
                    }
                });
    }

    /**
     * 展示加载对话框
     */
    protected void showLoadingDialog() {
        if (mDialog == null) {
            mDialog = WaitingDialog.newDialog(getActivity()).setMessage(R.string.login_ing);
            mDialog.setMessage("正在加载...");
            mDialog.setCancelable(false);
        }
        mDialog.show();
    }

    /**
     * 销毁加载对话框
     */
    protected void dismissLoadingDialog() {
        if (mDialog != null) {
            mDialog.dismiss();
        }
    }




}
